package org.example.controller;

import org.example.entity.Scene;
import org.example.entity.SceneDevice;
import org.example.service.SceneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

/**
 * 场景控制器
 */
@RestController
@RequestMapping("/scenes")
@CrossOrigin(origins = "*")
public class SceneController {
    
    @Autowired
    private SceneService sceneService;
    
    /**
     * 创建场景
     */
    @PostMapping
    public ResponseEntity<?> createScene(@Valid @RequestBody Scene scene) {
        try {
            Scene createdScene = sceneService.createScene(scene);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdScene);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 根据ID获取场景
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getSceneById(@PathVariable Long id) {
        Optional<Scene> scene = sceneService.findById(id);
        if (scene.isPresent()) {
            return ResponseEntity.ok(scene.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 根据用户ID获取场景
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Scene>> getScenesByUserId(@PathVariable Long userId) {
        List<Scene> scenes = sceneService.findByUserId(userId);
        return ResponseEntity.ok(scenes);
    }
    
    /**
     * 根据激活状态获取场景
     */
    @GetMapping("/user/{userId}/active/{isActive}")
    public ResponseEntity<List<Scene>> getScenesByActiveStatus(@PathVariable Long userId, @PathVariable Integer isActive) {
        List<Scene> scenes = sceneService.findByUserIdAndIsActive(userId, isActive);
        return ResponseEntity.ok(scenes);
    }
    
    /**
     * 搜索场景
     */
    @GetMapping("/user/{userId}/search")
    public ResponseEntity<List<Scene>> searchScenes(@PathVariable Long userId, @RequestParam String name) {
        List<Scene> scenes = sceneService.searchScenesByName(userId, name);
        return ResponseEntity.ok(scenes);
    }
    
    /**
     * 更新场景信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateScene(@PathVariable Long id, @Valid @RequestBody Scene scene) {
        try {
            scene.setId(id);
            Scene updatedScene = sceneService.updateScene(scene);
            return ResponseEntity.ok(updatedScene);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 更新场景状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateSceneStatus(@PathVariable Long id, @RequestBody SceneStatusRequest request) {
        try {
            Scene scene = sceneService.updateSceneStatus(id, request.getIsActive());
            return ResponseEntity.ok(scene);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 执行场景
     */
    @PostMapping("/{id}/execute")
    public ResponseEntity<?> executeScene(@PathVariable Long id, @RequestBody ExecuteSceneRequest request) {
        try {
            sceneService.executeScene(id, request.getUserId());
            return ResponseEntity.ok("场景执行成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 添加设备到场景
     */
    @PostMapping("/{sceneId}/devices")
    public ResponseEntity<?> addDeviceToScene(@PathVariable Long sceneId, @RequestBody AddDeviceRequest request) {
        try {
            SceneDevice sceneDevice = sceneService.addDeviceToScene(
                    sceneId, request.getDeviceId(), request.getDeviceStatus(), request.getDeviceProperties());
            return ResponseEntity.ok(sceneDevice);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 从场景中移除设备
     */
    @DeleteMapping("/{sceneId}/devices/{deviceId}")
    public ResponseEntity<?> removeDeviceFromScene(@PathVariable Long sceneId, @PathVariable Long deviceId) {
        try {
            sceneService.removeDeviceFromScene(sceneId, deviceId);
            return ResponseEntity.ok("设备从场景中移除成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 获取场景中的设备
     */
    @GetMapping("/{sceneId}/devices")
    public ResponseEntity<List<SceneDevice>> getSceneDevices(@PathVariable Long sceneId) {
        List<SceneDevice> devices = sceneService.getSceneDevices(sceneId);
        return ResponseEntity.ok(devices);
    }
    
    /**
     * 更新场景设备设置
     */
    @PutMapping("/{sceneId}/devices/{deviceId}")
    public ResponseEntity<?> updateSceneDevice(@PathVariable Long sceneId, @PathVariable Long deviceId, 
                                             @RequestBody UpdateSceneDeviceRequest request) {
        try {
            SceneDevice sceneDevice = sceneService.updateSceneDevice(
                    sceneId, deviceId, request.getDeviceStatus(), request.getDeviceProperties());
            return ResponseEntity.ok(sceneDevice);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 统计用户场景数量
     */
    @GetMapping("/user/{userId}/count")
    public ResponseEntity<Long> getSceneCount(@PathVariable Long userId) {
        long count = sceneService.countScenesByUserId(userId);
        return ResponseEntity.ok(count);
    }
    
    /**
     * 统计激活场景数量
     */
    @GetMapping("/user/{userId}/active-count")
    public ResponseEntity<Long> getActiveSceneCount(@PathVariable Long userId) {
        long count = sceneService.countActiveScenesByUserId(userId);
        return ResponseEntity.ok(count);
    }
    
    /**
     * 删除场景
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteScene(@PathVariable Long id) {
        try {
            sceneService.deleteScene(id);
            return ResponseEntity.ok("场景删除成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    // 内部类用于请求体
    public static class SceneStatusRequest {
        private Integer isActive;
        
        public Integer getIsActive() { return isActive; }
        public void setIsActive(Integer isActive) { this.isActive = isActive; }
    }
    
    public static class ExecuteSceneRequest {
        private Long userId;
        
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
    }
    
    public static class AddDeviceRequest {
        private Long deviceId;
        private Integer deviceStatus;
        private String deviceProperties;
        
        public Long getDeviceId() { return deviceId; }
        public void setDeviceId(Long deviceId) { this.deviceId = deviceId; }
        public Integer getDeviceStatus() { return deviceStatus; }
        public void setDeviceStatus(Integer deviceStatus) { this.deviceStatus = deviceStatus; }
        public String getDeviceProperties() { return deviceProperties; }
        public void setDeviceProperties(String deviceProperties) { this.deviceProperties = deviceProperties; }
    }
    
    public static class UpdateSceneDeviceRequest {
        private Integer deviceStatus;
        private String deviceProperties;
        
        public Integer getDeviceStatus() { return deviceStatus; }
        public void setDeviceStatus(Integer deviceStatus) { this.deviceStatus = deviceStatus; }
        public String getDeviceProperties() { return deviceProperties; }
        public void setDeviceProperties(String deviceProperties) { this.deviceProperties = deviceProperties; }
    }
}
